/**
 * Created by ROGSTAR on 2016/11/29.
 */
require.config(window.jshead);
require(['jquery', 'pages', "layer",'navigator','radialIndicator'], function ($, pg,layer) {
    layer.config({
        path: '/js/layer/'
    });

    radialIndicator.defaults.radius = 48;
    radialIndicator.defaults.barColor = "#fcb22f";
    radialIndicator.defaults.barBgColor = "#e8e8e8";
    radialIndicator.defaults.barWidth = 5;
    radialIndicator.defaults.percentage = true;
    radialIndicator.defaults.displayNumber = true;
    radialIndicator.defaults.fontSize = 26;
    radialIndicator.defaults.fontWeight = 'normal';
    $('#rate').radialIndicator();
    $('#rate').data('radialIndicator').value($('#rate').attr('data-value'));
    var itemId=decodeURI(window.location.href).split('?')[1];
    var itemCycleForCoupon=$('#itemCycleForCoupon').text();
    var amountC=0;
    var selectedId=null;
    var couponIcome1=0;
    var couponIcome2=0;
    var amountSelected=0;
    var couponId=null;
    //自动填入
    $('#autoValue').click(function () {

        var insertvalue = "";
        if(parseInt($('#accountMoney').text().replace(/,/g,""))<=parseInt($('#itemAccountLeft').text().replace(/,/g,"")))
        {
            insertvalue = parseInt($('#accountMoney').text().replace(/,/g,""))
        }else if(parseInt($('#accountMoney').text().replace(/,/g,""))>parseInt($('#itemAccountLeft').text().replace(/,/g,""))){
            insertvalue = parseInt($('#itemAccountLeft').text().replace(/,/g,""))
        }
        $('#usableMoney').val(insertvalue);


    });
    //图片预览
    picTab($('#imgLarge'),$('.slider'),0);
    function picTab(ele,allNum,currentNum) {
        allNum.click(function () {
            console.info($(this).index($(".slider")));
            currentNum = $(this).index($(".slider"));

            ele.show(300);
            var ImgSrc = $(this).attr('data-url');

            ele.css('background-image', 'url('+ImgSrc+')');
        });
        $('.close').click(function () {
            ele.hide(300);
            $('#payPassword_rsainput').val('');
            $(".guangbiao").css({"left":0});
            $(".sixDigitPassword").find("i").find("b").css({"display":"none"});
        });
        $('.left').click(function () {
            currentNum--;
            if (currentNum < 0) {
                currentNum = allNum.length - 1;
            }
            var ImgSrc = allNum.eq(currentNum).attr('data-url');
            ele.css('background-image', 'url('+ImgSrc+')');
        });

        $('.right').click(function () {
            currentNum++;
            if (currentNum > allNum.length - 1) {
                currentNum = 0;
            }
            var ImgSrc = allNum.eq(currentNum).attr('data-url');
            ele.css('background-image', 'url('+ImgSrc+')');
        })
    }


//tab切换
    $('#tabs div').click(function () {
        $(this).addClass('tab_active');
        var show=$('#contents .tab_content').eq($(this).index());
        show.show();
        $('#tabs div').not($(this)).removeClass('tab_active');
        $('#contents .tab_content').not(show).hide();
        if($(this).index()==2){
            //投标记录
            pg.paging(1, 8, "/item/investList", 'recordList', 'recordListFunc', {itemId:itemId}, '', '');
        }
        if($(this).index()==3){
            //还款计划
            pg.paging(1, 8, "/item/repayList", 'repayList', 'repayListFunc', {itemId:itemId}, '#repaypages', '');
        }
    });



//收益计算器
    $('#cacuClose').click(function () {
        $('#cacuPanel').hide(300);
        $('#reset').click();
    });
    $('.caculator').click(function () {
        $('#cacuPanel').show(300);
        var investCycle=parseFloat($('#investCycle').text());
        var investRate=parseFloat($('#investRate').text());
        var repayMethod=$('#repayMethod').text();
        var leftItemAccount=$('#investMoneyCalcu').attr('data-value');
        if(leftItemAccount && leftItemAccount.indexOf(','!=0)){
            var left=parseFloat(leftItemAccount.replace(/,/g,''));
        }
        var investMoney=0;
        $('#investMoneyCalcu').bind('keyup',function(){
            investMoney=$('#investMoneyCalcu').val();
            if(investMoney<=0){
                layer.tips('投资金额不能小于0',$('#investMoneyCalcu'));
            }else if(investMoney==''){
                layer.tips('请输入投资金额',$('#investMoneyCalcu'));
            }else if(investMoney > left){
                investMoney=parseFloat($('#investMoneyCalcu').val());
                layer.tips('投资金额不能大于项目余额',$('#investMoneyCalcu'));
            }
        })

        $('#cacu').click(function () {
            investMoney=$('#investMoneyCalcu').val();
            if(investMoney<=0){
                layer.tips('投资金额不能小于0',$('#investMoneyCalcu'));
            }else if(investMoney==''){
                layer.tips('请输入投资金额',$('#investMoneyCalcu'));
            }else if(investMoney > left){
                investMoney=parseFloat($('#investMoneyCalcu').val());
                layer.tips('投资金额不能大于项目余额',$('#investMoneyCalcu'));
            }else{
                investMoney=parseFloat($('#investMoneyCalcu').val());

                if(repayMethod=='先息后本'){
                    var interest=((investMoney * investRate*30)/36000).toFixed(4);
                    var interest1 =interest.toString().num2.substring(0,interest.toString().lastIndexOf('.')+3)
                    var principalInterest=(parseFloat(interest)*investCycle/30+investMoney).toFixed(4);
                    var principalInterest1 = principalInterest.toString().substring(0, principalInterest.toString().lastIndexOf('.')+3)
                    $('#intrerst_3').text(interest1);
                    $('#total_3').text(principalInterest1);
                }

                else if(repayMethod=='一次性还款'){
                    var everyIntrerst=(investMoney*investRate*investCycle/36000).toFixed(4);
                    var everyIntrerst1 = everyIntrerst.toString().substring(0, everyIntrerst.toString().lastIndexOf('.')+3)
                    var total=(investMoney*investRate*investCycle/36000+investMoney).toFixed(4)
                    var total1 = total.toString().substring(0, total.toString().lastIndexOf('.')+3)
                    $('#everyIntrerst_2').text(everyIntrerst1);
                    $('#total_2').text(total1);
                }

                else if(repayMethod=='等额本息'){
                   var investRate1 = investRate/1200 //月利率
                    var investCycle1 = investCycle/30// 投资月数
                    var allpayment = ((investMoney*investRate1*Math.pow(1+investRate1,investCycle1))/(Math.pow(1+investRate1,investCycle1)-1)).toFixed(4)
                    var allpayment1 = allpayment.toString().substring(0, allpayment.toString().lastIndexOf('.')+3)
                    var perRepayment = (allpayment*investCycle1).toFixed(4)
                    var perRepayment1 = perRepayment.toString().substring(0, perRepayment.toString().lastIndexOf('.')+3)
                    $('#intrerst_1').text(allpayment1);
                    $('#total_1').text(perRepayment1);
                }
            }




        });
        $('#reset').click(function () {
            $('#investMoneyCalcu').val('');
            if(repayMethod=='一次性还款'){
                $('#intrerst_3').text('');
                $('#total_3').text('');
            }else if(repayMethod=='先息后本'){
                $('#everyIntrerst_2').text('');
                $('#lastIntrerst_2').text('');
                $('#total_2').text('');
            }else if(repayMethod=='等额本息'){
                $('#intrerst_1').text('');
                $('#total_1').text('');
            }

        })
    });

    //充值
    $('.close').click(function () {
        $('#needRecharge').hide(300);
    });
    $('#rechargeCancle').click(function () {
        $('#needRecharge').hide(300);
    });



    $('#usableMoney').keyup(function(){
        var itemAccountLeft=parseFloat($('#itemAccountLeft').text().replace(/,/g,''));
        var usableMoney=$('#usableMoney').val();
        if(usableMoney>itemAccountLeft){
            layer.tips('投资金额不能大于项目余额','#usableMoney');
            $('#usableMoney').val(itemAccountLeft)
            return
        }
    })
//立即投资
    $('#investNormal').click(function () {
        $.ajax({
            type: "POST",
            url: " /user/info/getInfo",
            dataType: "json",
            async:false,
            success: function (data) {
                if(data.userRiskType==0 || !data.userRiskType){
                    layer.msg('您还未评估风险，即将为您前往风险评估');
                    var url=decodeURI(window.location.href);
                        $.cookie('the_cookie',url, {path: '/' });
                    setTimeout(function(){
                        window.location.href="/user/assessment?"+data.id;
                    },1500);
                }else{
                    var accountMoney=parseFloat($('#accountMoney').text().replace(/,/g,''));
                    var itemAccountLeft=parseFloat($('#itemAccountLeft').text().replace(/,/g,''));
                    var minInvestMoney=parseFloat($('#minInvestMoney').text().replace(/,/g,''));
                    var lock=$('#usableMoney').attr('data-value');
                    var usableMoney=$('#usableMoney').val();
                    if(usableMoney==''){
                        layer.tips('请输入投资金额','#usableMoney');
                        return
                    }
                    if(usableMoney==0){
                        layer.tips('投资金额不能为0','#usableMoney');
                        return
                    }
                    if(usableMoney>itemAccountLeft){
                        layer.tips('投资金额不能大于项目余额','#usableMoney');
                        return
                    }
                    if(usableMoney<minInvestMoney && itemAccountLeft>=minInvestMoney){
                        layer.tips('投资金额不能小于项目起投金额','#usableMoney');
                        return
                    }
                    if(usableMoney>accountMoney){
                        //账户余额不足
                        $('#needRecharge').show(300);
                        //充值
                        $('.close').click(function () {
                            $('#needRecharge').hide(300);
                        });
                        $('#rechargeCancle').click(function () {
                            $('#needRecharge').hide(300);
                        });

                    }
                    //定向密码校验
                    else if(lock=='isLock'){
                        var password=$('#lockPsw').val();
                        if(password=='' || password==undefined){
                            layer.tips('定向密码不能为空','#lockPsw');
                            return
                        }
                        $.ajax({
                            type: "POST",
                            dataType: "JSON",
                            data: {
                                itemId: itemId,
                                password:password

                            },
                            url: "/invest/password",
                            success: function (data) {

                                if(data.result=='success'){
                                    getPanel()
                                }else{
                                    layer.tips(data.messageText,'#lockPsw');
                                }


                            }
                        })

                    }else{
                        getPanel()
                    }
                    function getPanel(){
                        //弹出投资窗口,判断有无红包和加息券
                        $('#couponPanel').show(300);

                        //红包列表
                        $.ajax({
                            type: "POST",
                            dataType: "JSON",
                            data: {
                                cycle:itemCycleForCoupon,
                                amount:usableMoney,
                                itemId: itemId
                            },
                            url: "/invest/coupon",
                            async:false,
                            success: function (data) {

                                if(data.length==0){
                                    $('#hasNoCoupon').show();
                                    $('#hasCoupon').hide();
                                    couponId=null;
                                    $('#investAccountTotal').text(usableMoney+'元');
                                    $('#couponAmount').text('');
                                }else{
                                    $('#hasNoCoupon').hide();
                                    $('#hasCoupon').show();
                                    //显示列表
                                    var optionHtml='';

                                    for(var i=0;i<data.length;i++){
                                        if(data[i].couponName && data[i].couponName.length>4){
                                            data[i].couponName=data[i].couponName.substring(0,4)+'...';
                                        }
                                        optionHtml+='<option value='+data[i].amount+'/'+data[i].id+'>'+data[i].amount+'元、'+data[i].way+'、满'+data[i].requireAmount+'元可用</option>';
                                    }

                                    $('#selectCoupon').html(optionHtml);

                                    changeFunc();

                                    $('#selectCoupon').bind('change',changeFunc);

                                    $('#couponCheck').attr('checked',true);
                                    if($('#couponCheck').prop('checked')==false){
                                        $('#couponAmount').text('');
                                        amountSelected=0;
                                        couponId=null;
                                        $('#investAccountTotal').text(usableMoney+'元');
                                        // if($('#tiketCheck').prop('checked')==false){
                                        //     return;
                                        // }else{
                                        //     selectedId=$("#selectTiket").find("option:selected").val();
                                        // }
                                    }else{
                                        changeFunc();
                                    }
                                    $('#couponCheck').click(function () {//选择红包
                                        //--------------加息卷置空--------------

                                        $("#tiketCheck").attr("checked",false);
                                        $('#couponIncome').text('');
                                        selectedId=null;
                                        //--------------加息卷置空end--------------

                                        if($('#couponCheck').prop('checked')==false){
                                            $('#couponAmount').text('');
                                            amountSelected=0;
                                            couponId=null;
                                            $('#investAccountTotal').text(usableMoney+'元');
                                            // if($('#tiketCheck').prop('checked')==false){
                                            //     return;
                                            // }else{
                                            //     selectedId=$("#selectTiket").find("option:selected").val();
                                            // }
                                        }else{
                                            changeFunc();
                                        }
                                    });

                                    function changeFunc(){//首次出现弹窗判断红包加席卷选中情况。
                                        if($('#couponCheck').prop('checked')==false){
                                            amountSelected=0;
                                            couponId=null;
                                            $('#couponAmount').text('');
                                            $('#investAccountTotal').text(usableMoney+'元');
                                        }else{
                                            amountSelected=$("#selectCoupon").find("option:selected").val().split('/')[0];
                                            couponId=$("#selectCoupon").find("option:selected").val().split('/')[1];
                                            $('#investAccountTotal').text(usableMoney-amountSelected+'元');
                                            $('#couponAmount').html('+'+amountSelected+'元');
                                            if($('#tiketCheck').prop('checked')==false){
                                                selectedId=null
                                            }else{
                                                selectedId=$("#selectTiket").find("option:selected").val();
                                            }
                                            getIncomeTiket(selectedId,parseFloat(usableMoney));
                                        }
                                    }



                                }
                            }
                        });
                        //加息券列表
                        $.ajax({
                            type: "POST",
                            dataType: "JSON",
                            data: {
                                cycle:itemCycleForCoupon,
                                amount:usableMoney,
                                itemId: itemId
                            },
                            url: "/invest/ticket",
                            async:false,
                            success: function (data) {
                                //判断红包是否选中
                                function couponIsCheckedFuc(){
                                    if($('#tiketCheck').prop('checked')==false){
                                        selectedId=null
                                    }else{
                                        selectedId=$("#selectTiket").find("option:selected").val();
                                    }
                                    getIncomeTiket(selectedId,parseFloat(usableMoney));
                                }
                                if(data.length==0){
                                    $('#hasNoticket').show();
                                    $('#hasticket').hide();
                                    couponIsCheckedFuc()
                                }else{
                                    $('#hasNoticket').hide();
                                    $('#hasticket').show();
                                    //显示列表

                                    var optionHtml2='';

                                    for(var i=0;i<data.length;i++){
                                        if(data[i].ticketName && data[i].ticketName.length>4){
                                            data[i].ticketName=data[i].ticketName.substring(0,4)+'...';
                                        }
                                        optionHtml2+='<option value='+data[i].id+'>'+data[i].rate+'%/'+data[i].usefulLife+'天、'+data[i].way+'、满'+data[i].requireAmount+'元可用</option>';
                                    }

                                    $('#selectTiket').html(optionHtml2);
                                    $('#tiketCheck').click(function () {
                                        //-----------红包置空---------------------
                                        $("#couponCheck").attr("checked",false);
                                        $('#couponAmount').text('');
                                        couponId=null;
                                        $('#investAccountTotal').text(usableMoney+'元');
                                        //-----------红包置空end---------------------

                                        if($('#tiketCheck').prop('checked')==false){
                                            $('#couponIncome').text('');
                                            couponIsCheckedFuc()
                                        }else{
                                            couponIsCheckedFuc()
                                        }
                                    });
                                    $('#tiketCheck').attr('checked',true);
                                    $("#couponCheck").attr("checked",false);
                                    $('#couponAmount').text('');
                                    couponId=null;
                                    $('#investAccountTotal').text(usableMoney+'元');
                                    //-----------红包置空end---------------------

                                    if($('#tiketCheck').prop('checked')==false){
                                        $('#couponIncome').text('');
                                        couponIsCheckedFuc()
                                    }else{
                                        couponIsCheckedFuc()
                                    }

                                    changeFunc();
                                    function changeFunc(){
                                        if($('#selectTiket').prop('checked')==false){
                                            selectedId=null;
                                            $('#couponIncome').text('');
                                        }else{
                                            selectedId=$("#selectTiket").find("option:selected").val();
                                            couponIsCheckedFuc();
                                        }
                                        getIncomeTiket(selectedId,parseFloat(usableMoney));
                                    }

                                    $('#selectTiket').bind('change',changeFunc)
                                }
                            }
                        });
                    }
                    //计算加息券收益
                    function getIncomeTiket(ticketId,amount){
                        $.ajax({
                            type: "POST",
                            dataType: "JSON",
                            data: {
                                itemId: itemId,
                                amount:amount,
                                ticketId:ticketId
                            },
                            async: false,
                            url: "/invest/calculator",
                            success: function (data) {
                                $.ajax({
                                    type: "POST",
                                    dataType: "JSON",
                                    data: {
                                        itemId: itemId,
                                        amount:amount
                                    },
                                    async: false,
                                    url: "/invest/calculator",
                                    success: function (data) {
                                        $('#itemIncome').html(data.interest+'元');
                                        couponIcome1=data.interest;
                                    }
                                });


                                if(couponIcome1!=0){
                                    couponIcome2=(data.interest-couponIcome1).toFixed(2);
                                }
                                if(couponIcome2!=0){
                                    $('#couponIncome').html('+'+couponIcome2+'元');
                                }

                            }
                        })
                    }
                    $('.close').click(function () {
                        $('#couponPanel').hide(300)
                    })
                    $("#payPassword_rsainput").focus();
                }
            },
                error:function (data){
                }
            });
    });
    //立即投资
    $('#investFinal').click(function () {
        var usableMoney=parseFloat($('#usableMoney').val());
        var payPassword=$("#payPassword_rsainput").val();
        var leftmoney = parseFloat($('#itemAccountLeft').text().replace(/,/g,""));
        if(usableMoney>leftmoney){
            layer.msg('投资金额超出可投金额');
            return
        }else if($('#agreement').prop('checked')==false){
            layer.tips('是否同意借款协议','#agreement');
            return
        }else if(payPassword.length<1){
            layer.tips('请输入交易密码','.sixDigitPassword');
            return
        }
        var layerLoad = layer.load(1);
        $.ajax({
            type: "POST",
            dataType: "json",
            data: {
                amount:usableMoney,
                itemId:itemId,
                payPassword:payPassword,
                couponId:couponId,
                ticketId:selectedId
            },
            url: "/invest/buy",
            beforeSend: function () {
                // 禁用按钮防止重复提交
                $("#investFinal").attr({ disabled: "disabled" });
            },
            success: function (data) {
                layer.close(layerLoad);
                if(data.result=="fail"){
                    if(data.messageText){
                        layer.msg(data.messageText);
                    }else{
                        layer.msg('系统异常');
                    }
                    $("#investFinal").removeAttr("disabled");
                    $("#payPassword_rsainput").val('').focus();
                    $(".guangbiao").css({"left":0});
                    $(".sixDigitPassword").find("i").find("b").css({"display":"none"});
                }else{
                    layer.msg('投资成功');
                    setTimeout(function(){
                        window.location.reload();
                    },2000)
                }
            },
            error:function(data){
                layer.msg('通讯失败');
                setTimeout(function(){
                    $("#payPassword").val('');
                    $(".guangbiao").css({"left":0});
                    $(".sixDigitPassword").find("i").find("b").css({"display":"none"});
                },1000)

            }
        });
    });
    //计算年龄
    function   ages(str)
    {
        var   r   =   str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
        if(r==null)return   false;
        var   d=   new   Date(r[1],   r[3]-1,   r[4]);
        if   (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4])
        {
            var   Y   =   new   Date().getFullYear();
            $('#people_age').html(Y-r[1]+"岁");
        }
        $('#people_age').html("保密");
    }
    if($("#birthday").val()){
        ages($("#birthday").val());
    }else{
        $('#people_age').html("保密")
    }
    $('#sex').html($('#identifyCard').html().substr(14,3)%2?'男':'女');
    //支付弹框
    $("#payPassword_rsainput").bind("blur", function (){
        $(".sixDigitPassword span").removeClass("guangbiao");
    });
    $("#payPassword_rsainput").bind("focus", function (){
        $(".sixDigitPassword span").addClass("guangbiao");
        if($(".i-text").val().length==6){
            $(".guangbiao").css({"left":($(".i-text").val().length-1)*50});
        }else{
            $(".guangbiao").css({"left":($(".i-text").val().length)*50});
        }
    });
    $(".i-text").keyup(function() {
        var inp_v = $(this).val();
        var inp_l = inp_v.length;
        //$("p").html( "input的值为：" + inp_v +"; " + "值的长度为:" + inp_l);//测试用

        for( var x = 0; x<=6; x++)
        {
            //$("p").html( inp_l );//测试

            $(".sixDigitPassword").find("i").eq( inp_l ).prevAll("i").find("b").css({"display":"block"});
            $(".sixDigitPassword").find("i").eq( inp_l - 1 ).nextAll("i").find("b").css({"display":"none"});
            $(".guangbiao").css({"left":inp_l * 50});//光标位置
            if( inp_l == 0)
            {
                $(".sixDigitPassword").find("b").css({"display":"none"});
                $(".guangbiao").css({"left":0});
            }
            else if( inp_l == 6)
            {
                $(".sixDigitPassword").find("b").css({"display":"block"});
                $(".guangbiao").css({"left":5 * 50});
            }
        }
    });
    //支付页回车事件
    $(".bg_panel").keydown(function() {
        if (event.keyCode == "13") {//keyCode=13是回车键
            $('#investFinal').click();
        }
    });
    var url=decodeURI(window.location.href);
    $('#loginBtn').bind('click',function(){
        $.cookie('the_cookie',url, {path: '/' });
    });
});